//
//  MiscSDK.swift
//  Game105Client-mobile
//
//  Created by Developer001 on 2025/3/26.
//

import Foundation
import AppTrackingTransparency
import AdSupport

@objc class MiscSDK : NSObject, SDKDelegate {
    
    // 静态变量持有单例实例
    @MainActor
    static var instance: MiscSDK?
    
    var viewController :UIViewController?
    
    @MainActor
    @objc func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        print("@MiscSDK launched")
        
        MiscSDK.instance = self
        
        if let window = application.delegate?.window {
            viewController = window?.rootViewController
        }
        JsbSDK.onMsg("MiscSDK.requestInfoDictionary", handler: self.getInfoDictionary);
        JsbSDK.onMsg("MiscSDK.requestDeviceInfo", handler: self.getDeviceInfo);
        JsbSDK.onMsg("MiscSDK.requestIDFA", handler: self.getIDFA);
        JsbSDK.onMsg("MiscSDK.requestATA", handler: self.getAdvertisingTrackingAuthority);
        JsbSDK.onMsg("MiscSDK.requestHaptic", handler: self.haptic);
        JsbSDK.onMsg("MiscSDK.requestIsTestFlightBeta", handler: self.requestIsTestFlightBeta);
        
        
//        getAdvertisingTrackingAuthority();
        
//        print("Bundle.main.appStoreReceiptURL: \(String(describing: Bundle.main.appStoreReceiptURL))");
        
        return true
    }
    
    func getInfoDictionary(args:String?) {
        let infoDictionary = Bundle.main.infoDictionary;
        JsbSDK.sendMsg("MiscSDKManager.responseInfoDictionary", args: infoDictionary);
    }
    
    func getIDFA(args:String?) {
        let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        print("IDFA: \(idfa)")
        JsbSDK.sendMsg("MiscSDKManager.responseIDFA", args: ["IDFA": idfa])
    }
    
    @MainActor func getDeviceInfo(args:String?) {
        JsbSDK.sendMsg("MiscSDKManager.responseDeviceInfo", args: [
            "localizedModel": UIDevice.current.localizedModel,
            "systemName": UIDevice.current.systemName,
            "systemVersion": UIDevice.current.systemVersion,
            "model": UIDevice.current.model,
            "name": UIDevice.current.name,
            "phoneModel": getPhoneModel()
        ]);
    }
//    
    @MainActor func getPhoneModel() -> String {
        var systemInfo = utsname()
        uname(&systemInfo)
        let machine = withUnsafePointer(to: &systemInfo.machine) {
            $0.withMemoryRebound(to: CChar.self, capacity: 1) {
                String(cString: $0)
            }
        }
        return machine
    }
    
    func getAdvertisingTrackingAuthority(args:String?) {
        if #available(iOS 14, *) {
            let status = ATTrackingManager.trackingAuthorizationStatus
            switch status {
            case .denied:
                print("用户拒绝IDFA")
                JsbSDK.sendMsg("MiscSDKManager.responseATA", args: ["result": "denied"])
            case .authorized:
                print("用户允许IDFA")
                JsbSDK.sendMsg("MiscSDKManager.responseATA", args: ["result": "authorized"])
            case .notDetermined:
                print("用户未做选择或未弹窗IDFA")
                // 请求弹出用户授权框
                ATTrackingManager.requestTrackingAuthorization { status in
                    print("app追踪IDFA权限：\(status.rawValue)")
                    if (status.rawValue == 3) {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            JsbSDK.sendMsg("MiscSDKManager.responseATA", args: ["result": "authorized"])
                        }
                    } else {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                            JsbSDK.sendMsg("MiscSDKManager.responseATA", args: ["result": "denied"])
                        }
                    }
                }
            case .restricted:
                print("用户的IDFA权限受到限制")
                JsbSDK.sendMsg("MiscSDKManager.responseATA", args: ["result": "restricted"])
            @unknown default:
                break
            }
        } else {
            // Fallback on earlier versions
            if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
                print("用户开启了广告追踪IDFA")
                JsbSDK.sendMsg("MiscSDKManager.responseATA", args: ["result": "denied"])
            } else {
                print("用户关闭了广告追踪IDFA")
                JsbSDK.sendMsg("MiscSDKManager.responseATA", args: ["result": "authorized"])
            }
        }
    }
    
    @MainActor func haptic(args:String?) {
        print("@haptic", args as Any)
        if let jsonData = args?.data(using: .utf8) {
            do {
                if let json = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                    let style = json["style"] as? String
//                    print("@style is ", style as Any)
                    
                    var generator: UIImpactFeedbackGenerator;
                    if style == "light" {
                        generator = UIImpactFeedbackGenerator(style: .light)
                    } else if style == "medium" {
                        generator = UIImpactFeedbackGenerator(style: .medium)
                    } else if style == "heavy" {
                        generator = UIImpactFeedbackGenerator(style: .heavy)
                    } else if style == "soft" {
                        if #available(iOS 13.0, *) {
                            generator = UIImpactFeedbackGenerator(style: .soft)
                        } else {
                            generator = UIImpactFeedbackGenerator(style: .light)
                            // Fallback on earlier versions
                        }
                    } else {
                        if #available(iOS 13.0, *) {
                            generator = UIImpactFeedbackGenerator(style: .rigid)
                        } else {
                            generator = UIImpactFeedbackGenerator(style: .light)
                            // Fallback on earlier versions
                        }
                    }
                    generator.prepare()
                    generator.impactOccurred()
                    
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }
    
    func requestIsTestFlightBeta(args:String?) {
        let _isTestFlightBeta = isTestFlightBeta();
        JsbSDK.sendMsg("MiscSDKManager.responseIsTestFlightBeta", args: ["result": _isTestFlightBeta]);
    }
    
    func isTestFlightBeta() -> Bool {
        guard let receiptURL = Bundle.main.appStoreReceiptURL else {
            return false
        }
        // TestFlight 安装的收据路径包含 "sandboxReceipt"
        return receiptURL.lastPathComponent == "sandboxReceipt"
    }

}
